package org.example.logindemo.filter;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.logindemo.domain.entity.User;
import org.example.logindemo.enums.AppHttpCodeEnum;
import org.example.logindemo.exception.SystemException;
import org.example.logindemo.utils.JwtUtil;
import org.example.logindemo.utils.RedisCache;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor{

	@Resource
	private final RedisCache redisCache;

    public JwtInterceptor(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("Auth-Token");
		if(!StringUtils.hasText(token)){
			throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
		}

		//解析获取userid
		Claims claims = null;
		try {
			claims = JwtUtil.parseJWT(token);
		} catch (Exception e) {
			e.printStackTrace();
			//token超时  token非法
			//响应告诉前端需要重新登录
			throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
		}
		String userName = claims.getSubject();

		//从redis中获取用户信息
		User loginUser = redisCache.getCacheObject("login:" + userName);
		//如果获取不到
		if(Objects.isNull(loginUser)){
			//说明登录过期  提示重新登录
			throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
		}
		return true;
	}
}
